<template>
  <CustomNavBar title="开票记录" />
  <view class="history-page">
    <scroll-view scroll-y class="list-scroll" @scrolltolower="handleScrollToLower">
      <view v-for="item in history" :key="item.id" class="invoice-item" @click="goDetail(item)">
        <view class="item-top">
          <text class="item-title">{{ item.title }}</text>
          <text class="item-amount">¥{{ formatAmount(item.amount) }}</text>
        </view>

        <view class="item-time">
          <view class="left-col">
            <view class="time-left">
              <text class="time-label">开票时间：</text>
              <text class="time-value">{{ item.date }}</text>
            </view>
            <view class="item-actions">
              <view v-if="item.status === '已开票' || item.status === '已重开' || item.status === '已申请'" class="link" @click.stop="viewInvoice(item)">查看发票</view>
              <view v-if="item.status === '已作废'" class="link danger" @click.stop="deleteInvoice(item)">删除</view>
            </view>
          </view>
          <view class="status-square">
            <image class="status-stamp" :src="getStatusImage(item.status)" mode="aspectFit" />
          </view>
        </view>
        <!-- <view class="item-divider"></view> -->
		<view class="border-line" />
      </view>
      <view v-if="history.length === 0" class="empty-state">
        <image src="https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/images/empty-invoice.png" mode="widthFix" class="empty-image"></image>
        <text>暂无开票记录</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import CustomNavBar from '@/components/CustomNavBar.vue'
import InvoiceApi from '@/api/app/invoice.js'

// 示例数据（改为接口获取，保留注释便于联调）
// const history = ref([
//   { id: 1, title: '深圳市一诺程实业有限公司', amount: 90.00, date: '2025-08-11 09:00:00', status: '已开票' },
//   { id: 2, title: '个人', amount: 120.00, date: '2025-08-11 09:00:00', status: '已申请' },
//   { id: 3, title: '北京市科技有限公司', amount: 500.00, date: '2025-08-11 09:00:00', status: '已作废' },
// ]);
const history = ref([]);

const formatAmount = (v) => Number(v).toFixed(2);

// 分页状态
const pageNo = ref(1);
const pageSize = ref(20); // 默认20条
const hasMore = ref(true);
const loading = ref(false);

// 日期格式化：统一为 YYYY-MM-DD HH:mm:ss
const pad = (n) => String(n).padStart(2, '0');
const formatDateTime = (v) => {
  if (!v) return '';
  const d = new Date(v);
  if (isNaN(d.getTime())) {
    // 如果是字符串但 Date 解析失败，直接返回原值以保证展示
    return typeof v === 'string' ? v : '';
  }
  const y = d.getFullYear();
  const m = pad(d.getMonth() + 1);
  const day = pad(d.getDate());
  const h = pad(d.getHours());
  const mi = pad(d.getMinutes());
  const s = pad(d.getSeconds());
  return `${y}-${m}-${day} ${h}:${mi}:${s}`;
};

// 状态映射：根据你提供的 invoiceStatus 枚举
const KNOWN_STATUS = ['未开票','已申请','已开票','申请重开','已重开','已作废'];
const mapStatus = (s) => {
  if (KNOWN_STATUS.includes(s)) return s;
  const n = Number(s);
  if (Number.isNaN(n)) {
    // 兼容旧文案“开票中”，映射为“已申请”
    if (s === '开票中') return '已申请';
    return s || '已开票';
  }
  switch (n) {
    case 0: return '未开票';
    case 1: return '已申请';
    case 2: return '已开票';
    case 3: return '申请重开';
    case 4: return '已重开';
    case 5: return '已作废';
    default: return '已开票';
  }
};

const mapHistoryItem = (item) => ({
  id: item.id ?? item.historyId ?? item.invoiceId ?? item.pendingId,
  title: item.headerName ?? item.title ?? (item.headerId ? `${item.headerId}` : '—'),
  amount: Number(item.amount ?? 0),
  date: formatDateTime(item.issueDate ?? item.createdAt),
  status: mapStatus(item.invoiceStatus),
  invoiceUrl: item.invoiceUrl ?? ''
});

const loadHistory = async (isLoadMore = false) => {
  if (loading.value) return;
  loading.value = true;
  try {
    const params = {
      pageNo: isLoadMore ? pageNo.value : 1,
      pageSize: pageSize.value
    };
    const res = await InvoiceApi.getInvoicedList(params);
    const list = Array.isArray(res) ? res : (res?.list || res?.data || []);
	console.log('原始数据:', list);
    const mapped = list.map(mapHistoryItem);
	console.log('映射后数据:', mapped);

    if (isLoadMore) {
      history.value = [...history.value, ...mapped];
    } else {
      history.value = mapped;
      pageNo.value = 1;
    }

    hasMore.value = mapped.length === pageSize.value;
    if (hasMore.value) pageNo.value++;
  } catch (e) {
    console.error('获取开票历史失败:', e);
    uni.showToast({ title: '获取历史失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

const handleScrollToLower = () => {
  if (hasMore.value && !loading.value) {
    loadHistory(true);
  }
};

onMounted(() => {
  loadHistory(false);
});

// 状态对应的圆形印章图片
const getStatusImage = (status) => {
  const s = mapStatus(status);
  if (s === '已开票' || s === '已重开') {
    return '@/static/images/invoice/state1_slices/state1.png';
  }
  if (s === '已作废') {
    return '@/static/images/invoice/state3_slices/state3.png';
  }
  // 未开票、已申请、申请重开
  return '@/static/images/invoice/state2_slices/state2.png';
};

const viewInvoice = (item) => {
  const url = item?.invoiceUrl;
  if (url) {
    uni.setClipboardData({
      data: url,
      success: () => uni.showToast({ title: '发票链接已复制', icon: 'none' })
    });
  } else {
    uni.showToast({ title: '暂无发票链接', icon: 'none' });
  }
};

const deleteInvoice = (item) => {
  uni.showModal({
    title: '删除确认',
    content: '确定删除该记录吗？',
    success: (res) => {
      if (res.confirm) {
        history.value = history.value.filter(i => i.id !== item.id);
      }
    }
  });
};

const goDetail = (item) => {
  if (!item || !item.id) return
  uni.navigateTo({ url: `/pages/invoice/detail?id=${item.id}` })
}
</script>

<style scoped>
.history-page {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
}
.list-scroll {
	background-color: #fff;
  flex: 1;
  box-sizing: border-box;
  /* padding: 30rpx; */
}
.invoice-item {
  position: relative;
  background-color: #fff;
  padding: 30rpx 60rpx 30rpx;
  /* margin: 0 0 20rpx 0; */
}
.item-top {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
}
.item-title {
  font-size: 30rpx;
  font-weight: 500;
  /* color: #222; */
  line-height: 1.5;
}
.item-amount {
  font-size: 32rpx;
  /* color: #333; */
}
.item-time {
  margin-top: 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.left-col {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-height: 100rpx; /* 与右侧状态方框高度一致，保证上下分布 */
}
.time-left {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  color: #7B7B7D;
}
.time-label {
  color: #7B7B7D;
  margin-right: 12rpx;
}
.item-actions {
  margin-top: 16rpx;
  display: flex;
  align-items: center;
}
.link {
  color: #1DCFB7;
  font-size: 26rpx;
}
.link.danger {
  color: #7B7B7D;
}

.status-square {
  width: 100rpx;
  height: 100rpx;
  border: 2rpx dashed #7B7B7D;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.status-stamp {
  width: 84rpx;
  height: 84rpx;
}

/* .item-divider {
  margin-top: 24rpx;
  height: 1rpx;
  background: #eee;
  transform: scaleY(0.5);
} */
/* 边框线 */
.border-line {
  height: 1px;
  background-color: #DCDFEC;
  margin: 30rpx -60rpx -30rpx 0; 	/* 按需调整 */
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 200rpx;
  color: #7B7B7D;
}
.empty-image {
  width: 300rpx;
  margin-bottom: 20rpx;
}
</style>